<script setup lang="ts">
import { TypeUserPageVoI, TypeUserVoI } from '@/api/user/user_types.ts'
import * as userApi from '@/api/user/user_api_index';
import { useUserStore } from '@/store/modules/user_store'
import {$bus} from '@/event_bus/event_bus_index.ts'
import UserAddEditFormDialog from './use_add_edit_form_dialog.vue'
import { onMounted, ref } from 'vue';
import { storeToRefs } from 'pinia';
import { ElMessage, ElMessageBox } from 'element-plus';
import ElSvgIcon from '@/components/el-svg-icon/el_svg_icon_index.vue';
import { NslUtilDownUpLoad } from '@/utils/down_up_load/NslUtilDownUpLoad.ts';
import { EnumHttpMime } from '@/types/global/enums/enums_types';
import UserImportDialog from './user_import_dialog.vue';
import Pagination from '@/components/pagination/pagination_index.vue'

// const emits = defineEmits(['handleQuery', 'openDialog', 'resetQuery'])
const loading = ref(false)
const pageData = ref<TypeUserPageVoI>({ list: [], total: 0 }) // 用户分页数据
const userStore = useUserStore()
const { queryParamsRef } = storeToRefs(userStore)

$bus.on('user-table-query', () => {
    handleQuery()
})

const removeIds = ref<string[]>([])
const userAddEditFormDialogRef = ref()
const userImportDialog = ref()

const openUserFormDialog = (userId?: string) => {
    // emits('openDialog', dialogType, userId)
    console.log('userAddEditFormDialog', userAddEditFormDialogRef)

    userAddEditFormDialogRef.value!.openDialog(userId)
}

async function handleQuery() {
    loading.value = true
    userApi
        .getUserPage(queryParamsRef.value)
        .then(({ data }) => {
            console.log('in handelQuery data =', data)
            pageData.value = data
        })
        .finally(() => {
            console.log('######')
            loading.value = false
        })
}

const handleDelete = (userId?: string) => {
    const userIdsArray = [userId || removeIds.value].join(',')
    if (!userIdsArray) {
        ElMessage.warning('请勾选删除项')
        return
    }
    ElMessageBox.confirm('确认删除用户?', '警告', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
    }).then(() => {
        userApi
            .deleteUsers(userIdsArray)
            .then(() => {
                ElMessage.success('删除成功')
                //如果在第一页，保持不变
                //如果不在第一页
                //a. 删除数量如果等于pageData.length，则pageNum-1
                //b. 如果删除数量<pageData.length，则pageNum不变
                if (queryParamsRef.value && queryParamsRef.value.pageNum && queryParamsRef.value.pageNum > 1) {
                    if (userIdsArray.length === pageData.value.list.length) {
                        queryParamsRef.value.pageNum--
                    }
                }
                handleQuery()
            })
            .catch(() => {
                ElMessage.error('删除失败')
            })
    })
}

const openImportDialog = () => {
    userImportDialog.value.openDialog()
}

/** 下载导入模板 */
function downloadTemplate() {
    userApi.downloadTemplateApi().then((response: any) => {
        const fileData = response.data
        const fileName = decodeURIComponent(
            response.headers['content-disposition'].split(';')[1].split('=')[1],
        )
        // const fileType =
        //     'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet;charset=utf-8';
        NslUtilDownUpLoad.downloadFile(fileData, EnumHttpMime.OFFICE_XLSX, fileName);
    })
}

/** 导出用户 */
function exportQueryUser() {
    userApi.exportQueryUser(queryParamsRef.value).then((response: any) => {
        const fileData = response.data
        const fileName = decodeURIComponent(
            response.headers['content-disposition'].split(';')[1].split('=')[1],
        )
        // const fileType =
        //     'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet;charset=utf-8';
        NslUtilDownUpLoad.downloadFile(fileData, EnumHttpMime.OFFICE_XLSX, fileName);
    })
}
/**
 * 导出所有用户数据
 */
 async function exportAllUser(){
    const response = await userApi.exportAllUser()
    const fileData = response.data
    const fileName = decodeURIComponent(
        response.headers['content-disposition'].split(';')[1].split('=')[1],
    )
    // const fileType =
    //     'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet;charset=utf-8';
    NslUtilDownUpLoad.downloadFile(fileData, EnumHttpMime.OFFICE_XLSX, fileName);
}
/**
 * todo:
 * 导出已选数据
 */
function exportSelected(){

}

/** 重置密码 */
function resetPassword(row: TypeUserVoI) {
    console.log('row', row)

    ElMessageBox.prompt('请输入用户「' + row.username + '」的新密码', '重置密码', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
    })
        .then(({ value }) => {
            if (!value) {
                ElMessage.warning('请输入新密码')
                return false
            }
            userApi.updateUserPassword(row.id!, value).then(() => {
                ElMessage.success('密码重置成功，新密码是：' + value)
            })
        })
        .catch(() => {
            ElMessage.warning('密码未修改。')
        })
}
/** 行选中 */
function handleSelectionChange(selection: any) {
    removeIds.value = selection.map((item: any) => item.id)
}

onMounted(() => {
    handleQuery()
})
</script>
<template>
    <el-card shadow="never" class="table-container">
        <template #header>
            <div class="buttons">
                <div>
                    <el-button
                        v-hasPerm="['sys:user:add']"
                        type="success"
                        @click="openUserFormDialog()"
                        ><ElSvgIcon a-icon-name="el-icon-delete" :aSize="15"/>新增</el-button
                    >
                    <el-button
                        v-hasPerm="['sys:user:delete']"
                        type="danger"
                        :disabled="removeIds.length === 0"
                        @click="handleDelete()"
                        ><ElSvgIcon a-icon-name="el-icon-delete" :aSize="15"/> &nbsp;删除所选</el-button
                    >
                </div>
                <div>
                    <el-dropdown split-button>
                        导入
                        <template #dropdown>
                            <el-dropdown-menu>
                                <el-dropdown-item @click="downloadTemplate">
                                    <ElSvgIcon a-icon-name="el-icon-download"/>下载模板</el-dropdown-item
                                >
                                <el-dropdown-item @click="openImportDialog">
                                    <ElSvgIcon a-icon-name="el-icon-upload"/>导入数据</el-dropdown-item
                                >
                            </el-dropdown-menu>
                        </template>
                    </el-dropdown>

                    <el-dropdown split-button>
                        导出
                        <template #dropdown>
                            <el-dropdown-menu>
                                <el-dropdown-item @click="exportAllUser">
                                    <ElSvgIcon a-icon-name="el-icon-download"/>导出所有</el-dropdown-item
                                >
                                <el-dropdown-item @click="exportQueryUser">
                                    <ElSvgIcon a-icon-name="el-icon-bottom"/>导出筛选</el-dropdown-item
                                >
                            </el-dropdown-menu>
                        </template>
                    </el-dropdown>
                </div>
            </div>
        </template>

        <el-table
            v-loading="loading"
            :data="pageData!.list"
            @selection-change="handleSelectionChange"
        >
            <el-table-column type="selection" width="50" align="center" />
            <el-table-column key="id" label="编号" align="center" prop="id" width="100" />
            <el-table-column key="username" label="用户名" align="center" prop="username" />
            <el-table-column label="用户昵称" width="120" align="center" prop="nickname" />

            <el-table-column label="性别" width="100" align="center" prop="genderLabel" />

            <el-table-column label="部门" width="120" align="center" prop="deptName" />
            <el-table-column label="手机号码" align="center" prop="mobile" width="120" />

            <el-table-column label="状态" align="center" prop="status">
                <template #default="scope">
                    <el-tag :type="scope.row.status == 1 ? 'success' : 'info'">{{
                        scope.row.status == 1 ? '启用' : '禁用'
                    }}</el-tag>
                </template>
            </el-table-column>
            <el-table-column label="创建时间" align="center" prop="createTime" width="180" />
            <el-table-column label="操作" fixed="right" width="220">
                <template #default="scope">
                    <el-button
                        v-hasPerm="['sys:user:reset_pwd']"
                        type="primary"
                        size="small"
                        link
                        @click="resetPassword(scope.row)"
                        ><i-ep-refresh-left />重置密码</el-button
                    >
                    <el-button
                        v-hasPerm="['sys:user:edit']"
                        type="primary"
                        link
                        size="small"
                        @click="openUserFormDialog(scope.row.id)"
                        ><i-ep-edit />编辑</el-button
                    >
                    <el-button
                        v-hasPerm="['sys:user:delete']"
                        type="primary"
                        link
                        size="small"
                        @click="handleDelete(scope.row.id)"
                        ><i-ep-delete />删除</el-button
                    >
                </template>
            </el-table-column>
        </el-table>

        <Pagination
            v-if="pageData!.total > 0"
            v-model:total="pageData!.total"
            v-model:currentPage="queryParamsRef.pageNum"
            v-model:pageSzie="queryParamsRef.pageSize"
            @pagination="handleQuery"
        />
    </el-card>

            
    <UserAddEditFormDialog ref="userAddEditFormDialogRef" />
    <UserImportDialog ref="userImportDialog" />
</template>
<style lang="scss" scoped>
.buttons{
    display:flex;
    justify-content:space-between;
}
</style>
